<template>
  <div class="patrol">
    <van-nav-bar
        left-arrow
        @click-left="onClickLeft"
        title="合同管理"
    />
    <van-form @submit="onSubmit">
      <div class="uploader-div" style="margin-top: 20px">
        <van-uploader v-model="contractFileList" accept="image/*" multiple :max-count="3" :after-read="afterRead"
                      :before-delete="beforeDelete"/>
        <div class="uploader-text">合同照片</div>
      </div>
      <div class="uploader-div" style="margin-top: 30px;">
        <van-field
            readonly
            clickable
            name="合同开始日期"
            :value="startDate"
            label="合同开始日期"
            placeholder="点击选择开始日期"
            @click="showCalendar1 = true"
        />
        <van-calendar v-model="showCalendar1" @confirm="onConfirm1" :show-confirm="false" type="single"
                      :min-date="minDate" :max-date="maxDate" :default-date="defaultDate1"/>
        <van-field
            readonly
            clickable
            name="合同结束日期"
            :value="endDate"
            label="合同结束日期"
            placeholder="点击选择结束日期"
            @click="showCalendar2 = true"
        />
        <van-calendar v-model="showCalendar2" @confirm="onConfirm2" :show-confirm="false" type="single"
                      :min-date="minDate" :max-date="maxDate" :default-date="defaultDate2"/>
        <div class="top-btn">
          <van-button round block type="info" native-type="submit">保存</van-button>
        </div>
      </div>
    </van-form>

  </div>
</template>

<script>
import {
  contractGet,
  contractSave,
  contractUpload,
  contractDel, become
} from "@/api/operator";
import {getLocalOpenId} from "@/utils/wxUtil";
import {formatDateNoH} from "@/utils";

export default {
  data() {
    return {
      machineId: this.$route.query.id,
      contractFileList: [],
      fileList: [],
      showCalendar1: false,
      showCalendar2: false,
      minDate: new Date(1970, 0, 1),
      maxDate: new Date(2099, 11, 31),
      startDate: '',
      endDate: '',
      defaultDate1: '',
      defaultDate2: ''
    };
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },
    onConfirm1(date) {
      date = formatDateNoH(date)
      this.startDate = date
      this.showCalendar1 = false
    },
    onConfirm2(date) {
      date = formatDateNoH(date)
      this.endDate = date
      this.showCalendar2 = false
    },
    onSubmit: function () {
      let params={
        machineId: this.machineId,
        operatorId: getLocalOpenId(),
        startDate: this.startDate,
        endDate: this.endDate
      }
      contractSave(params).then(res => {
        this.$toast.success("保存成功！")
      })
    },
    afterRead(file, detail) {
      if (file.length > 0) {
        file.map((item, index) => {
          item.status = 'uploading'
          item.message = '上传中...'
          this.doUploadImg(item, '1')
        })
      } else {
        file.status = 'uploading'
        file.message = '上传中...'
        this.doUploadImg(file, '1')
      }
    },
    beforeDelete(file, detail) {
      this.$dialog.confirm({
        title: '删除提示',
        message: '确认要删除该图片？',
      }).then(res => {
        let index = detail.index;
        let obj = this.fileList[index]
        if (obj) {
          let params = {
            id: obj.id
          }
          contractDel(params).then(res => {
            this.fileList.splice(index, 1)
            this.contractFileList.splice(index, 1)
          }).catch(res => {
          })
        }
      })
      return false
    },
    doUploadImg(file) {
      if (file.file.size > 1 * 1048576) { // 超出1M进行压缩，否则不压缩
        this.imageCompress(file.content).then((result) => {
          const params = {
            openId: getLocalOpenId(),
            machineId: this.machineId,
            base64Str: result.split(',')[1]
          }
          contractUpload(params).then(res => {
            file.status = 'done'
            file.message = ''
            let result = {
              id: res.data.id,
              url: res.data.url
            }
            this.fileList.push(result);
          }).catch(res => {
            file.status = 'failed';
            file.message = '上传失败';
          });
        })
      } else {
        const params = {
          openId: getLocalOpenId(),
          machineId: this.machineId,
          base64Str: file.content.split(',')[1]
        }
        contractUpload(params).then(res => {
          file.status = 'done'
          file.message = ''
          let result = {
            id: res.data.id,
            url: res.data.url
          }
          this.fileList.push(result);
        }).catch(res => {
          file.status = 'failed';
          file.message = '上传失败';
        });
      }
    },
    imageCompress(base64) { // 压缩图片
      let Img = new Image()
      let dataURL = ''
      Img.src = base64
      let p = new Promise(function (resolve, reject) {
        Img.onload = function () { // 要先确保图片完整获取到，这是个异步事件
          let canvas = document.createElement('canvas') // 创建canvas元素
          let width = Img.width // 确保canvas的尺寸和图片一样
          let height = Img.height
          // 默认将长宽设置为图片的原始长宽，这样在长宽不超过最大长度时就不需要再处理
          let ratio = width / height
          let maxLength = 1000
          let newHeight = height
          let newWidth = width
          // 在长宽超过最大长度时，按图片长宽比例等比缩小
          if (width > maxLength || height > maxLength) {
            if (width > height) {
              newWidth = maxLength
              newHeight = maxLength / ratio
            } else {
              newWidth = maxLength * ratio
              newHeight = maxLength
            }
          }
          ;
          canvas.width = newWidth
          canvas.height = newHeight
          canvas.getContext('2d').drawImage(Img, 0, 0, newWidth, newHeight) // 将图片绘制到canvas中
          dataURL = canvas.toDataURL('image/jpeg', 0.5) // 转换图片为dataURL
          resolve(dataURL)
        }
      })
      return p
    }
  },
  mounted() {
    let params = {
      id: this.machineId
    }
    contractGet(params).then(res => {
      if (res) {
        this.startDate = formatDateNoH(res.data.startDate)
        this.endDate = formatDateNoH(res.data.endDate)
        if (res.data.imgs) {
          res.data.imgs.forEach((item, index, arr) => {
            let result = {
              id: item.id,
              url: item.url
            }
            this.contractFileList.push(result)
            this.fileList.push(result)
          })
        }
      }
      if(this.startDate){
        let arr = this.startDate.split('-')
        this.defaultDate1 = new Date(arr[0]/1, arr[1]/1 - 1, arr[2]/1)
      }
      if(this.endDate){
        let arr = this.endDate.split('-')
        this.defaultDate2 = new Date(arr[0]/1, arr[1]/1 - 1, arr[2]/1)
      }
    })
  }
}
</script>

<style lang="less" scoped>
.patrol {
  text-align: center;

  .uploader-div {
    margin-top: 10px;
    padding: 5px;

    .uploader-text {
      padding: 10px;
    }
  }
}

</style>
